package com.iot.gateway.aspectj.converter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.iot.gateway.annotation.FieldConverter;

import java.io.IOException;

/**
 * JSON字符串转对象
 * @param <T>
 */
public class JsonToObjectConverter<T> implements FieldConverter {

    private final Class<T> targetClass;

    public JsonToObjectConverter(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public Object convert(Object value) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue((String) value, targetClass);
        } catch (IOException e) {
            throw new IllegalArgumentException("JSON解析失败", e);
        }
    }

}
